#pragma  once

#include "gl_include.h"
#include "ELShaderProgram.h"
#include <thread>
#include <mutex>

NS_BEGIN(elloop);


class Event
{
public:
	~Event()
	{
		Stalling.notify_all();
	}
	void Wait()
	{
		std::unique_lock<std::mutex> UniqueLock(StallingLock);
		if (IsWakeup)
		{
			IsWakeup = false;
		}
		Stalling.wait(UniqueLock, [&]() { return IsWakeup; });

		/*std::unique_lock UniqueLock(StallingLock);
		Counter--;
		Stalling.wait(UniqueLock, [&]() { return Counter == 0; });*/
		//Stalling.wait(UniqueLock);
	}
	bool Wait(uint32_t Time)
	{
		std::unique_lock<std::mutex> UniqueLock(StallingLock);
		if (IsWakeup)
		{
			IsWakeup = false;
			return true;
		}
		std::chrono::time_point<std::chrono::system_clock> Now = std::chrono::system_clock::now() + std::chrono::milliseconds(Time);
		return Stalling.wait_until(UniqueLock, Now, [&]() {return IsWakeup; });


		/*std::unique_lock UniqueLock(StallingLock);
		Counter--;
		std::chrono::time_point<std::chrono::system_clock> Now = std::chrono::system_clock::now() + std::chrono::milliseconds(Time);
		return Stalling.wait_until(UniqueLock, Now, [&]() {return Counter == 0; });*/
	}
	void Wakeup()
	{

		std::unique_lock<std::mutex> UniqueLock(StallingLock);
		IsWakeup = true;
		Stalling.notify_all();

		/*std::unique_lock UniqueLock(StallingLock);
		Counter++;
		Stalling.notify_all();*/
	}
private:
	std::mutex StallingLock;
	std::condition_variable Stalling;
	//int32_t Counter = 0;
	bool IsWakeup = false;
};

class RotateRectangle : public ShaderProgram
{
public:
    static RotateRectangle*     create();
    void                        begin()     override;
    void                        end()       override;
    void                        render()    override;

    attribute                   _position;
    uniform                     _mvp;
    attribute                   _color;

	Event AuxiliaryRHIThreadEvent;
	std::thread  RunAuxiliaryRHIThread;
protected:
    bool                        init();
    RotateRectangle()
    {
        _vsFileName = "shaders/color_rectangle_vs.glsl";
        _fsFileName = "shaders/color_rectangle_fs.glsl";
    }
    ~RotateRectangle()
    {
		RunAuxiliaryRHIThread.detach();
	}
};



NS_END(elloop);